/**
 * degradation.js - 电机性能退化数据管理模块
 */

// API基本路径
const DEGRADATION_API_BASE = '/api/feibiao/degradation';

// 对应AmArchivesDegradationController @RequestMapping("/api/feibiao/degradation")

// 日期格式化
function formatDateTime(date) {
    if (!date) return '--';
    
    try {
        const dateObj = new Date(date);
        if (isNaN(dateObj.getTime())) return '--';
        
        // 格式化日期部分
        const year = dateObj.getFullYear();
        const month = String(dateObj.getMonth() + 1).padStart(2, '0');
        const day = String(dateObj.getDate()).padStart(2, '0');
        
        // 对于带时间的日期，添加时间部分
        if (date.includes('T') || date.includes(':')) {
            const hours = String(dateObj.getHours()).padStart(2, '0');
            const minutes = String(dateObj.getMinutes()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}`;
        }
        
        // 只有日期部分
        return `${year}-${month}-${day}`;
    } catch (e) {
        console.error('日期格式化错误:', e);
        return '--';
    }
}

// 格式化数字，保留2位小数
function formatNumber(num) {
    if (num === null || num === undefined) return '--';
    return parseFloat(num).toFixed(2);
}

// 获取状态对应的CSS类
function getStatusClass(value, warningThreshold, criticalThreshold) {
    if (value === null || value === undefined) return '';
    return value >= criticalThreshold ? 'status-critical' : 
           value >= warningThreshold ? 'status-warning' : 'status-good';
}

/**
 * 性能退化列表功能
 */
// 加载性能退化数据列表
function loadDegradationList(page = 0, size = 15) {
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
    
    fetch(`${DEGRADATION_API_BASE}?page=${page}&size=${size}`)
        .then(response => {
            if (!response.ok) {
                console.error('API请求失败:', response.status, response.statusText);
                return response.text().then(text => {
                    try {
                        // 尝试解析为JSON以获取更多错误信息
                        const errorData = JSON.parse(text);
                        console.error('错误详情 (JSON):', errorData);
                        if (errorData.message) {
                            throw new Error(`服务器错误 (${response.status}): ${errorData.message}`);
                        }
                    } catch (e) {
                        // 如果不是JSON或解析失败
                        console.error('错误详情 (Text):', text);
                    }
                    throw new Error(`服务器错误 (${response.status}): ${text || response.statusText}`);
                });
            }
            return response.json();
        })
        .then(data => {
            renderDegradationTable(data);
        })
        .catch(error => {
            console.error('获取性能退化数据失败:', error);
            mainContent.innerHTML = `
                <div class="error-container">
                    <h2>加载数据失败</h2>
                    <p>尝试加载URL: ${DEGRADATION_API_BASE}?page=${page}&size=${size}</p>
                    <p>错误信息: ${error.message}</p>
                    <div class="error-actions">
                        <button class="btn btn-primary" onclick="loadDegradationList()">重试</button>
                        <button class="btn btn-info" onclick="testDegradationAPI()">测试API</button>
                        <button class="btn btn-default" onclick="loadFeiBiaoContent('base')">返回电机基本信息</button>
                    </div>
                </div>
            `;
            showMessage('获取性能退化数据失败: ' + error.message, 'error');
        });
}

// 渲染性能退化数据表格
function renderDegradationTable(data) {
    const mainContent = document.getElementById('mainContent');
    
    let html = `
        <div class="content-header">
            <h2 class="content-title">电机性能退化数据管理</h2>
            <div class="header-actions">
                <button class="btn btn-primary" onclick="showDegradationForm()">新增</button>
            </div>
        </div>
        
        <div class="search-box">
            <input type="text" class="search-input" id="searchInput" placeholder="输入电机ID搜索...">
            <button class="search-btn" onclick="searchDegradation()">搜索</button>
        </div>
        
        <div class="table-responsive">
        <table class="data-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>电机ID</th>
                    <th>测量时间</th>
                    <th>效率下降(%)</th>
                    <th>功率下降(kW)</th>
                    <th>剩余寿命(小时)</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
    `;
    
    if (data.content && data.content.length > 0) {
        data.content.forEach(item => {
            // 根据数值确定显示的类别样式
            const efficiencyClass = getStatusClass(item.efficiencyDegradation, 5, 15);
            const powerClass = getStatusClass(item.powerDegradation, 5, 15);
            
            html += `
                <tr>
                    <td>${item.degradationId || ''}</td>
                    <td>${item.motorId || ''}</td>
                    <td>${formatDateTime(item.measurementTime)}</td>
                    <td><span class="status-badge ${efficiencyClass}">${formatNumber(item.efficiencyDegradation)}%</span></td>
                    <td><span class="status-badge ${powerClass}">${formatNumber(item.powerDegradation)} kW</span></td>
                    <td>${formatNumber(item.remainingLifePrediction)} h</td>
                    <td class="table-actions">
                        <a href="javascript:void(0)" onclick="viewDegradation(${item.degradationId})">查看</a>
                        <a href="javascript:void(0)" onclick="editDegradation(${item.degradationId})">编辑</a>
                        <a href="javascript:void(0)" class="delete" onclick="deleteDegradation(${item.degradationId})">删除</a>
                    </td>
                </tr>
            `;
        });
    } else {
        html += '<tr><td colspan="7" style="text-align:center;">暂无数据</td></tr>';
    }
    
    html += `
            </tbody>
        </table>
        </div>
    `;
    
    // 添加分页控件
    if (data.totalPages > 0) {
        html += `
            <ul class="pagination">
                <li class="${data.number <= 0 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${data.number <= 0 ? 'void(0)' : 'loadDegradationList(' + (data.number - 1) + ')'}">上一页</a>
                </li>
        `;
        // 页码
        for (let i = 0; i < data.totalPages; i++) {
            if (i === data.number) {
                html += `<li class="active"><a href="javascript:void(0)">${i + 1}</a></li>`;
            } else {
                html += `<li><a href="javascript:void(0)" onclick="loadDegradationList(${i})">${i + 1}</a></li>`;
            }
        }
        html += `
                <li class="${data.number >= data.totalPages - 1 ? 'disabled' : ''}">
                    <a href="javascript:void(0)" onclick="${data.number >= data.totalPages - 1 ? 'void(0)' : 'loadDegradationList(' + (data.number + 1) + ')'}">下一页</a>
                </li>
            </ul>
        `;
    }
    
    mainContent.innerHTML = html;
}

// 搜索性能退化数据
function searchDegradation() {
    const keyword = document.getElementById('searchInput').value.trim();
    // 重置页码并加载数据
    const page = 0;
    const size = 15;
    
    // 构建搜索URL，只支持电机ID精确查找
    let url = `${DEGRADATION_API_BASE}?page=${page}&size=${size}`;
    if (keyword) {
        url += `&motorId=${encodeURIComponent(keyword)}`;
    }
    
    // 显示加载中
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = '<div class="loading">数据加载中...</div>';
    
    // 发起请求
    fetch(url)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            renderDegradationTable(data);
        })
        .catch(error => {
            console.error('搜索失败:', error);
            showMessage('搜索失败: ' + error.message, 'error');
        });
}

// 显示性能退化数据表单
function showDegradationForm(data = null) {
    const isEdit = !!data;
    const mainContent = document.getElementById('mainContent');
    
    const formTitle = isEdit ? '编辑性能退化数据' : '新增性能退化数据';
    const submitButtonText = isEdit ? '更新' : '保存';
    
    // 格式化日期时间值
    let measurementTimeValue = '';
    if (isEdit && data.measurementTime) {
        const date = new Date(data.measurementTime);
        measurementTimeValue = date.toISOString().slice(0, 16); // 格式化为YYYY-MM-DDThh:mm
    }
    
    // 构建表单HTML
    mainContent.innerHTML = `
        <div class="content-header">
            <h2 class="content-title">${formTitle}</h2>
            <div class="header-actions">
                <button class="btn btn-default" onclick="loadDegradationList()"><i class="fa fa-list"></i> 返回列表</button>
            </div>
        </div>
        
        <div class="form-container">
        <form id="degradationForm" class="data-form" onsubmit="event.preventDefault(); saveDegradation(this, ${isEdit});">
            ${isEdit ? `<input type="hidden" name="degradationId" value="${data.degradationId}">` : ''}
            
            <div class="form-group">
                <label for="motorId">电机ID</label>
                <input type="text" id="motorId" name="motorId" class="form-control" value="${isEdit ? data.motorId : ''}" required>
                <small class="form-text">必须是已存在的电机ID</small>
            </div>
            
            <div class="form-group">
                <label for="measurementTime">测量时间</label>
                <input type="datetime-local" id="measurementTime" name="measurementTime" class="form-control" value="${measurementTimeValue}" required>
            </div>
            
            <div class="form-group">
                <label for="efficiencyDegradation">效率下降(%)</label>
                <input type="number" id="efficiencyDegradation" name="efficiencyDegradation" step="0.01" class="form-control" value="${isEdit && data.efficiencyDegradation ? data.efficiencyDegradation : ''}" required>
            </div>
            
            <div class="form-group">
                <label for="powerDegradation">功率下降(kW)</label>
                <input type="number" id="powerDegradation" name="powerDegradation" step="0.01" class="form-control" value="${isEdit && data.powerDegradation ? data.powerDegradation : ''}" required>
            </div>
            
            <div class="form-group">
                <label for="remainingLifePrediction">剩余寿命预测(小时)</label>
                <input type="number" id="remainingLifePrediction" name="remainingLifePrediction" step="0.01" class="form-control" value="${isEdit && data.remainingLifePrediction ? data.remainingLifePrediction : ''}" required>
            </div>
            
            <div class="form-actions">
                <button type="submit" class="btn btn-primary">${submitButtonText}</button>
                <button type="button" class="btn btn-default" onclick="loadDegradationList()">取消</button>
            </div>
        </form>
        </div>
    `;
}

// 保存性能退化数据
function saveDegradation(form, isEdit) {
    if (!form.checkValidity()) {
        form.reportValidity();
        return;
    }
    
    const formData = new FormData(form);
    const data = {};
    formData.forEach((value, key) => {
        data[key] = value;
    });
    
    // 数字类型处理
    if (data.efficiencyDegradation) data.efficiencyDegradation = parseFloat(data.efficiencyDegradation);
    if (data.powerDegradation) data.powerDegradation = parseFloat(data.powerDegradation);
    if (data.remainingLifePrediction) data.remainingLifePrediction = parseFloat(data.remainingLifePrediction);
    
    const url = isEdit 
        ? `${DEGRADATION_API_BASE}/${data.degradationId}` 
        : `${DEGRADATION_API_BASE}`;
    
    const method = isEdit ? 'PUT' : 'POST';
    
    fetch(url, {
        method: method,
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('网络响应错误');
        }
        return response.json();
    })
    .then(() => {
        showMessage(`${isEdit ? '更新' : '创建'}性能退化数据成功`, 'success');
        loadDegradationList();
    })
    .catch(error => {
        console.error(`${isEdit ? '更新' : '创建'}性能退化数据失败:`, error);
        showMessage(`${isEdit ? '更新' : '创建'}失败: ` + error.message, 'error');
    });
}

// 查看性能退化数据详情
function viewDegradation(degradationId) {
    fetch(`${DEGRADATION_API_BASE}/${degradationId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            showDegradationDetail(data);
        })
        .catch(error => {
            console.error('获取详情失败:', error);
            showMessage('获取详情失败: ' + error.message, 'error');
        });
}

// 显示性能退化数据详情
function showDegradationDetail(data) {
    const mainContent = document.getElementById('mainContent');
    let html = `
        <div class="content-header">
            <h2 class="content-title">性能退化数据详情</h2>
            <button class="btn btn-default" onclick="loadDegradationList()"><i class="fa fa-list"></i> 返回列表</button>
        </div>
        <div class="data-detail">
            <div class="detail-group"><label>ID:</label><div>${data.degradationId || '--'}</div></div>
            <div class="detail-group"><label>电机ID:</label><div>${data.motorId || '--'}</div></div>
            <div class="detail-group"><label>电机型号:</label><div>${data.motorType || '--'}</div></div>
            <div class="detail-group"><label>生产厂商:</label><div>${data.manufacturer || '--'}</div></div>
            <div class="detail-group"><label>测量时间:</label><div>${formatDateTime(data.measurementTime) || '--'}</div></div>
            <div class="detail-group"><label>效率下降(%):</label><div>${formatNumber(data.efficiencyDegradation)}%</div></div>
            <div class="detail-group"><label>功率下降(kW):</label><div>${formatNumber(data.powerDegradation)}</div></div>
            <div class="detail-group"><label>剩余寿命预测(小时):</label><div>${formatNumber(data.remainingLifePrediction)}</div></div>
            <div class="detail-actions">
                <button class="btn btn-primary" onclick="editDegradation(${data.degradationId})"><i class="fa fa-edit"></i> 编辑</button>
                <button class="btn btn-danger" onclick="deleteDegradation(${data.degradationId})"><i class="fa fa-trash"></i> 删除</button>
                <button class="btn btn-default" onclick="loadDegradationList()"><i class="fa fa-list"></i> 返回列表</button>
            </div>
        </div>
    `;
    mainContent.innerHTML = html;
}

// 编辑性能退化数据
function editDegradation(degradationId) {
    fetch(`${DEGRADATION_API_BASE}/${degradationId}`)
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应错误');
            }
            return response.json();
        })
        .then(data => {
            showDegradationForm(data);
        })
        .catch(error => {
            console.error('获取编辑信息失败:', error);
            showMessage('获取编辑信息失败: ' + error.message, 'error');
        });
}

// 删除性能退化数据
function deleteDegradation(degradationId) {
    if (!confirm('确定要删除此性能退化数据吗？此操作不可恢复。')) {
        return;
    }
    
    fetch(`${DEGRADATION_API_BASE}/${degradationId}`, {
        method: 'DELETE'
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('网络响应错误');
        }
        showMessage('删除性能退化数据成功', 'success');
        loadDegradationList();
    })
    .catch(error => {
        console.error('删除失败:', error);
        showMessage('删除失败: ' + error.message, 'error');
    });
}

// 消息提示函数
function showMessage(message, type = 'info') {
    // 检查是否有main.js中定义的全局showMessage函数，并且不是当前函数本身
    if (typeof window.showMessage === 'function' && window.showMessage !== showMessage) {
        // 如果全局已有且不是自身，则使用该函数
        window.showMessage(message, type);
    } else {
        // 否则创建一个简单的提示
        const messageContainer = document.getElementById('messageContainer') || document.createElement('div');
        
        if (!document.getElementById('messageContainer')) {
            messageContainer.id = 'messageContainer';
            messageContainer.className = 'message-container';
            document.body.appendChild(messageContainer);
        }
        
        const messageElement = document.createElement('div');
        messageElement.className = `message message-${type}`;
        messageElement.textContent = message;
        
        messageContainer.appendChild(messageElement);
        
        // 3秒后自动移除
        setTimeout(() => {
            messageElement.classList.add('message-hiding');
            setTimeout(() => {
                messageContainer.removeChild(messageElement);
            }, 300);
        }, 3000);
    }
}

// 确保所有函数都是全局可访问的
if (typeof window !== 'undefined') {
    // 导出性能退化数据函数
    window.loadDegradationList = loadDegradationList;
    window.renderDegradationTable = renderDegradationTable;
    window.searchDegradation = searchDegradation;
    window.showDegradationForm = showDegradationForm;
    window.saveDegradation = saveDegradation;
    window.viewDegradation = viewDegradation;
    window.showDegradationDetail = showDegradationDetail;
    window.editDegradation = editDegradation;
    window.deleteDegradation = deleteDegradation;
    
    // 工具函数
    window.formatDateTime = formatDateTime;
    window.formatNumber = formatNumber;
    window.getStatusClass = getStatusClass;
}

// 验证API可访问性
function testDegradationAPI() {
    console.log('正在测试性能退化数据API...');
    
    const mainContent = document.getElementById('mainContent');
    mainContent.innerHTML = `
        <div class="content-header">
            <h2 class="content-title">性能退化数据API测试</h2>
            <div class="header-actions">
                <button class="btn btn-primary" onclick="loadDegradationList()">返回列表</button>
                <button class="btn btn-default" onclick="loadFeiBiaoContent('base')">返回电机基本信息</button>
            </div>
        </div>
        
        <div class="api-test-container">
            <div class="test-status">正在测试API端点，请稍候...</div>
            <div id="testResults" class="test-results"></div>
        </div>
    `;
    
    const testResults = document.getElementById('testResults');
    
    // 测试多个API端点
    const endpoints = [
        { url: DEGRADATION_API_BASE, method: 'GET', name: '列表查询(主接口)' },
        { url: `${DEGRADATION_API_BASE}/by-motor?motorId=TEST`, method: 'GET', name: '电机ID查询' },
        { url: `${DEGRADATION_API_BASE}/1`, method: 'GET', name: '单条记录查询' }
    ];
    
    let allPassed = true;
    let completedTests = 0;
    let testDetails = [];
    
    // 按顺序测试各个端点
    endpoints.forEach((endpoint, index) => {
        fetch(endpoint.url, { method: endpoint.method })
            .then(response => {
                const statusClass = response.ok ? 'success' : 'error';
                const statusText = response.ok ? '成功' : '失败';
                
                return response.text().then(text => {
                    let errorDetails = '';
                    if (!response.ok) {
                        allPassed = false;
                        let errorMessage = '';
                        try {
                            // 尝试解析JSON错误信息
                            const errorJson = JSON.parse(text);
                            errorMessage = errorJson.message || errorJson.error || text;
                        } catch (e) {
                            // 如果不是JSON，直接使用文本
                            errorMessage = text;
                        }
                        
                        errorDetails = `
                            <div class="error-details">
                                <p><strong>状态码:</strong> ${response.status}</p>
                                <p><strong>错误详情:</strong> ${errorMessage || '无详细信息'}</p>
                            </div>
                        `;
                        
                        // 保存测试详情
                        testDetails.push({
                            endpoint: endpoint.url,
                            success: false,
                            status: response.status,
                            error: errorMessage
                        });
                    } else {
                        let responseData = '';
                        try {
                            const jsonData = JSON.parse(text);
                            responseData = JSON.stringify(jsonData, null, 2).substring(0, 100) + '...';
                        } catch (e) {
                            responseData = text.substring(0, 100) + '...';
                        }
                        
                        errorDetails = `
                            <div class="success-details">
                                <p><strong>响应预览:</strong></p>
                                <pre class="response-preview">${responseData}</pre>
                            </div>
                        `;
                        
                        // 保存测试详情
                        testDetails.push({
                            endpoint: endpoint.url,
                            success: true,
                            status: response.status
                        });
                    }
                    
                    testResults.innerHTML += `
                        <div class="test-result ${statusClass}">
                            <div class="test-name">${endpoint.name} (${endpoint.method} ${endpoint.url})</div>
                            <div class="test-status">状态: ${response.status} ${response.statusText} - ${statusText}</div>
                            ${errorDetails}
                        </div>
                    `;
                    
                    completedTests++;
                    if (completedTests === endpoints.length) {
                        showTestSummary(allPassed, testDetails);
                    }
                });
            })
            .catch(error => {
                allPassed = false;
                testResults.innerHTML += `
                    <div class="test-result error">
                        <div class="test-name">${endpoint.name} (${endpoint.method} ${endpoint.url})</div>
                        <div class="test-status">状态: 请求失败 - ${error.message}</div>
                        <div class="error-details">
                            <p>请求无法完成，可能是网络问题或服务器未运行</p>
                        </div>
                    </div>
                `;
                
                // 保存测试详情
                testDetails.push({
                    endpoint: endpoint.url,
                    success: false,
                    error: error.message,
                    networkError: true
                });
                
                completedTests++;
                if (completedTests === endpoints.length) {
                    showTestSummary(allPassed, testDetails);
                }
            });
    });
    
    function showTestSummary(allPassed, testDetails) {
        const testStatus = document.querySelector('.test-status');
        testStatus.className = `test-status ${allPassed ? 'success' : 'error'}`;
        testStatus.textContent = allPassed ? 
            'API测试完成，所有端点可访问！' : 
            'API测试完成，部分端点存在问题！';
            
        // 分析测试结果
        const diagnosis = analyzeTestResults(testDetails);
        
        testResults.innerHTML += `
            <div class="test-summary">
                <h3>诊断结果</h3>
                <p>${allPassed ? '所有API端点工作正常！' : '检测到以下问题：'}</p>
                ${!allPassed ? `
                <div class="diagnosis-details">
                    <div class="diagnosis-problem">
                        <h4>问题描述</h4>
                        <p>${diagnosis.problem}</p>
                    </div>
                    <div class="diagnosis-solution">
                        <h4>可能的解决方案</h4>
                        <ul>
                            ${diagnosis.solutions.map(solution => `<li>${solution}</li>`).join('')}
                        </ul>
                    </div>
                </div>
                
                <div class="diagnosis-tips">
                    <h4>服务器日志检查提示</h4>
                    <p>建议检查后端服务器的以下日志位置：</p>
                    <ul>
                        <li>Spring Boot 控制台日志</li>
                        <li>application.log 文件</li>
                        <li>MySQL/数据库错误日志</li>
                    </ul>
                    <p>常见的500错误类型：</p>
                    <ul>
                        <li>NullPointerException：空指针异常</li>
                        <li>DataIntegrityViolationException：数据完整性违规</li>
                        <li>JpaSystemException：JPA系统异常</li>
                        <li>ConstraintViolationException：约束违规异常</li>
                        <li>EntityNotFoundException：实体未找到异常</li>
                    </ul>
                </div>
                ` : ''}
            </div>
        `;
    }
    
    function analyzeTestResults(testDetails) {
        // 检查是否所有测试都失败了
        const allFailed = testDetails.every(test => !test.success);
        
        // 检查是否有网络错误
        const hasNetworkErrors = testDetails.some(test => test.networkError);
        
        // 只有主列表接口失败，而其他接口可能成功
        const onlyMainFailed = !testDetails[0].success && testDetails.slice(1).some(test => test.success);
        
        // 如果服务器返回500错误
        const has500Error = testDetails.some(test => test.status === 500);
        
        // 如果服务器返回404错误
        const has404Error = testDetails.some(test => test.status === 404);
        
        // 构建诊断信息
        let problem = '';
        let solutions = [];
        
        if (hasNetworkErrors) {
            problem = "无法连接到服务器API。这可能是网络问题或服务器未运行。";
            solutions = [
                "确认后端服务器正在运行",
                "检查网络连接",
                "验证API路径配置是否正确",
                "检查浏览器控制台是否有CORS错误"
            ];
        } else if (allFailed && has404Error) {
            problem = "所有API端点返回404错误。这表明API路径配置可能不正确或API尚未实现。";
            solutions = [
                "检查Controller中的@RequestMapping路径是否为'/api/feibiao/degradation'",
                "确认Controller类是否正确注册和加载",
                "检查Spring Boot应用是否正确启动并扫描到Controller"
            ];
        } else if (has500Error) {
            problem = "服务器返回500内部错误。这通常表示后端代码执行过程中出现异常。";
            solutions = [
                "检查服务器日志以获取详细的异常堆栈信息",
                "确认数据库中是否存在am_archives_degradation表",
                "确认表结构与AmArchivesDegradation实体类定义匹配",
                "检查am_archives_base表中是否有电机记录(作为外键引用)",
                "验证数据库连接配置和权限设置",
                "检查JPA配置和Entity映射是否正确",
                "检查@Table注解中的表名是否与数据库中的表名一致",
                "检查实体类中的@Column注解字段名是否与数据库中的列名一致",
                "验证外键关系在数据库中是否正确配置",
                "检查@JoinColumn设置是否正确"
            ];
        } else if (onlyMainFailed) {
            problem = "主列表API端点失败，但其他端点可能成功。这可能是分页查询相关的问题。";
            solutions = [
                "检查Pageable参数处理是否正确",
                "确认分页相关配置是否正确",
                "检查数据库中是否有足够的测试数据"
            ];
        } else {
            problem = "API测试发现多个问题，需要进一步调查。";
            solutions = [
                "检查服务器日志获取详细错误信息",
                "确认数据库表结构与实体类定义匹配",
                "确认必要的关联表和外键数据存在",
                "检查Controller和Service实现是否有逻辑错误",
                "验证数据库连接配置"
            ];
        }
        
        return { problem, solutions };
    }
}
